<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/20
 * Time: 15:45
 */

namespace app\admin\service\business\Alone\Access;


use app\admin\service\BaseService;
use app\admin\service\business\Alone\Access\Models\MixedModel;

/**
 * Class AccessMenuService
 *
 * @property-read MixedModel $mixed
 *
 * @package app\admin\service\business\Alone\Access
 */
class AccessMenuService extends BaseService
{
    protected $rely = [
        'mixed' => MixedModel::class,
    ];

    /**
     * 菜单列表
     *
     * @param bool $isShow
     * @return array
     */
    public function boot(bool $isShow = false)
    {
        $menus = $isShow ? $this->mixed->getMenuList()->toArray() : $this->handlerRoleMenu();

        // 处理菜单
        $menus = handlerCateList(array_unique($menus, SORT_REGULAR), 'parent_id');
        foreach ($menus as $k => $v) {
            if ($v['parent_id']) unset($menus[$k]);
        }

        // 赋值
        return array_values($menus);
    }

    /**
     * 处理角色下的菜单
     *
     * @return array
     */
    private function handlerRoleMenu(): array
    {
        list($roles, $menus) = [$this->data['roles'], []];

        // 角色列表
        foreach ($roles as $role) {
            // 菜单列表
            $menu = $role->menus->toArray();

            // 处理菜单格式
            array_reduce($menu, function ($result, $value) use (&$menus) {
                $menus[] = [
                    'id' => $value['id'],
                    'title' => $value['title'],
                    'icon' => $value['icon'],
                    'uri' => $value['uri'],
                    'parent_id' => $value['parent_id']
                ];
            });
        }

        return $menus;
    }
}
